package fstvis;

public class ComparisonStats extends Stats {
	public ComparisonStats(Field a, Field b) {

		Field1D fx1d = a.getField1D();
		
		double[] fx = fx1d.getField();
		double[] fy = b.getField1D().getField();
		int l = fx1d.getLength();

		double sum_xy = 0;
		double sum_x2 = 0, sum_x = 0;
		double sum_y2 = 0, sum_y = 0;
		double sum_x_minus_y_2 = 0;

		double sum_mne = 0, sum_mnb = 0, sum_mfe = 0, sum_mfb = 0;
		double threshold = 1e-7;
		int l1 = 0; // Count the values USED (we filter out values under |threshold|)

		double max = fx[1], min = fx[1];
		
		for (int i = 0; i<l; i++) {

			// used for correlation coefficient
			sum_x  += fx[i];
			sum_x2 += Math.pow(fx[i], 2);

			sum_y  += fy[i];
			sum_y2 += Math.pow(fy[i], 2);
			
			sum_xy += fx[i]*fy[i];
			//

			// Used for MSE
			sum_x_minus_y_2 += Math.pow(fx[i] - fy[i], 2);

			if (Math.abs(fx[i]) > threshold && Math.abs(fy[i]) > threshold) {
				l1++;

				// mne
				sum_mne += Math.abs(fx[i] - fy[i])/fx[i];
				
				// mne
				sum_mne += (fx[i] - fy[i])/fx[i];
				
				// mfe
				sum_mfe += Math.abs(fx[i] - fy[i])/(fx[i] + fy[i]);
				
				// mfb
				sum_mfb += (fx[i] - fy[i])/(fx[i] + fy[i]);
			}

			min = Math.min(Math.min(fx[i], fy[i]), min);
			max = Math.max(Math.max(fx[i], fy[i]), max);
		}

		double numerator = sum_xy - (sum_x * sum_y)/l;
		double denomenator = (sum_x2 - Math.pow(sum_x, 2)/l) * (sum_y2 - Math.pow(sum_y, 2)/l);
		denomenator = Math.sqrt(denomenator);

		this.setR(numerator/denomenator);

		this.setMSE(sum_x_minus_y_2/l);
		this.setMNE(sum_mne/l1);
		this.setMNB(sum_mnb/l1);
		this.setMFE(2*sum_mfe/l1);
		this.setMFB(2*sum_mfb/l1);
		this.setMin(min);
		this.setMax(max);
	}
}
